package org.teamh.gui.mapeditor;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import java.awt.Point;

import org.teamh.connection.Connection;
import org.teamh.connection.MapDownload;
import org.teamh.connection.handler.ConnectionHandler;
import org.teamh.game.repository.MapRepository;
import org.teamh.gui.Event;
import org.teamh.gui.GUI;
import org.teamh.gui.createGame.ErrorPopup;
import org.teamh.gui.mapeditor.filechooser.NiftyFileChooser.NiftyFileChooseInvoker;
import org.teamh.gui.mapeditor.popups.SavePopup;
import org.teamh.logic.lobby.Map;

import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.NiftyEventSubscriber;
import de.lessvoid.nifty.controls.ListBox;
import de.lessvoid.nifty.controls.ListBoxSelectionChangedEvent;
import de.lessvoid.nifty.controls.TextField;
import de.lessvoid.nifty.elements.Element;
import de.lessvoid.nifty.input.NiftyInputEvent;
import de.lessvoid.nifty.screen.KeyInputHandler;
import de.lessvoid.nifty.screen.Screen;
import de.lessvoid.nifty.screen.ScreenController;

public class MapEditorController implements ScreenController {
	private GUI gui;
	private MapEditorScreen mapEditorScreen;
	private Screen mapEditorNiftyScreen;
	private Element informationtext;
	public String backgroundPath;
	private boolean exitClicked = false;
	private int button;
	private File[] files;
	private File latestFile = null;
	private boolean popupOpen = false;

	private enum Clickable {
		START, PATH, BLOCKED, FREE, NOTHING
	}

	private Clickable active = Clickable.NOTHING;
	private SavePopup savePopup;
	private ErrorPopup errorPopup;
	private boolean loggedIn;
	private boolean uploadClicked;
	private boolean loginButtonClicked;
	private boolean cancelClicked = false;

	public MapEditorController(GUI gui, MapEditorScreen mapEditorScreen) {
		this.gui = gui;
		this.mapEditorScreen = mapEditorScreen;
	}

	/*
	 * NIFTY Functions
	 */

	@Override
	public void onEndScreen() {

	}

	@Override
	public void onStartScreen() {

	}

	@Override
	public void bind(Nifty nifty, Screen mapEditorScreen) {
		this.mapEditorNiftyScreen = mapEditorScreen;
		this.informationtext = mapEditorScreen
				.findElementByName("informationtext");
		this.mapEditorScreen.initPopup();
		this.savePopup = new SavePopup(gui);
		this.errorPopup = new ErrorPopup(gui);
	}

	// Hoveraktionen
	public void showInformationtext(String name) {
		hideAllInformationtexts();
		mapEditorNiftyScreen.findElementByName(name).show();
	}

	public void showInformationtextAndHovereffect(String name) {// name wird
																// �bergeben
																// und dann der
																// entsprechende
																// name des
																// informationstextes
																// und des
																// rahmens
																// zusammengebaut
																// und mit
																// diesem namen
																// dann die
																// entsprechende
																// funktion
																// aufgerufen
		hideAllInformationtexts();
		String informationtextname = "informationtext" + name;
		String Hovereffectname = "Hovereffect" + name;
		mapEditorNiftyScreen.findElementByName(informationtextname).show();
		mapEditorNiftyScreen.findElementByName(Hovereffectname).show();
	}

	// Ende Hoveraktionen
	public void hideAllInformationtexts() {
		mapEditorNiftyScreen.findElementByName("informationtextStart").hide();
		mapEditorNiftyScreen.findElementByName("informationtextDraw").hide();
		mapEditorNiftyScreen.findElementByName("informationtextGo").hide();
		mapEditorNiftyScreen.findElementByName("informationtextNoGo").hide();
	}

	public void hideAllInformationtextsAndHovereffekts() {
		mapEditorNiftyScreen.findElementByName("informationtextStart").hide();
		mapEditorNiftyScreen.findElementByName("informationtextDraw").hide();
		mapEditorNiftyScreen.findElementByName("informationtextGo").hide();
		mapEditorNiftyScreen.findElementByName("informationtextNoGo").hide();
		mapEditorNiftyScreen.findElementByName("HovereffectStart").hide();
		mapEditorNiftyScreen.findElementByName("HovereffectDraw").hide();
		mapEditorNiftyScreen.findElementByName("HovereffectGo").hide();
		mapEditorNiftyScreen.findElementByName("HovereffectNoGo").hide();
	}

	public void hideAllBordersClicked() {
		mapEditorNiftyScreen.findElementByName("borderStartClicked").hide();
		mapEditorNiftyScreen.findElementByName("borderDrawClicked").hide();
		mapEditorNiftyScreen.findElementByName("borderGoClicked").hide();
		mapEditorNiftyScreen.findElementByName("borderNoGoClicked").hide();
	}

	// Festlegen der Panelclickactionen Start/Draw/Go/Nogo
	public void startclick() {
		hideAllBordersClicked();
		mapEditorNiftyScreen.findElementByName("borderStartClicked").show();
		active = Clickable.START;
	}

	public void drawclick() {
		hideAllBordersClicked();
		mapEditorNiftyScreen.findElementByName("borderDrawClicked").show();
		active = Clickable.PATH;
	}

	public void goclick() {
		hideAllBordersClicked();
		mapEditorNiftyScreen.findElementByName("borderGoClicked").show();
		active = Clickable.FREE;

	}

	public void nogoclick() {
		hideAllBordersClicked();
		mapEditorNiftyScreen.findElementByName("borderNoGoClicked").show();
		active = Clickable.BLOCKED;
	}

	private void reactOnEnter(String elementName) {
		mapEditorNiftyScreen.findElementByName(elementName).addInputHandler(
				new KeyInputHandler() {
					@Override
					public boolean keyEvent(NiftyInputEvent inputEvent) {
						if (inputEvent == null)
							return false;
						switch (inputEvent) {
						case SubmitText:
							loginbuttonclick();
							return true;
						default:
							break;
						}
						return false;
					}
				});
	}

	public void chooseClickFunction(int X, int Y) {
		if (!popupOpen) {

			Y = gui.getHeight() - Y;
			if (button == 0) {
				switch (active) {
				case START:
					gui.getMapEditorScreen().getMapEditorFunctions()
							.setStartPoint(new Point(X, Y));
					break;
				case PATH:
					gui.getMapEditorScreen().getMapEditorFunctions()
							.addPointsToPath(new Point(X, Y), true);
					break;
				case FREE:
					gui.getMapEditorScreen().getMapEditorFunctions()
							.constructible(new Point(X, Y), 0);
					break;
				case BLOCKED:
					gui.getMapEditorScreen().getMapEditorFunctions()
							.constructible(new Point(X, Y), 2);
					break;
				case NOTHING:
					break;
				default:
					break;
				}
			} else {
				switch (active) {
				case START:
					break;
				case PATH:
					gui.getMapEditorScreen().getMapEditorFunctions()
							.deletePath(new Point(X, Y));
					break;
				case FREE:
					gui.getMapEditorScreen().getMapEditorFunctions()
							.constructible(new Point(X, Y), 2);
					break;
				case BLOCKED:
					gui.getMapEditorScreen().getMapEditorFunctions()
							.constructible(new Point(X, Y), 0);
					break;
				case NOTHING:
					break;
				default:
					break;
				}
			}
		}
	}

	public void chooseLeftClickFunction(int X, int Y) {
		Y = gui.getHeight() - Y;
		switch (active) {
		case START:
			gui.getMapEditorScreen().getMapEditorFunctions()
					.setStartPoint(new Point(X, Y));
			break;
		case PATH:
			gui.getMapEditorScreen().getMapEditorFunctions()
					.addPointsToPath(new Point(X, Y), true);
			break;
		case FREE:
			gui.getMapEditorScreen().getMapEditorFunctions()
					.constructible(new Point(X, Y), 0);
			break;
		case BLOCKED:
			gui.getMapEditorScreen().getMapEditorFunctions()
					.constructible(new Point(X, Y), 2);
			break;
		case NOTHING:
			break;
		default:
			break;
		}
	}

	public void chooseRightClickFunction(int X, int Y) {
		Y = gui.getHeight() - Y;

	}

	public void mouseReleased(int X, int Y) {
		Y = gui.getHeight() - Y;
		gui.getMapEditorScreen().getMapEditorFunctions()
				.mouseReleased(new Point(X, Y));
	}

	public void changeVisibility(String showname, String hidename) {
		show(showname);
		hide(hidename);
	}

	public void hide(String hidename) {
		if (mapEditorNiftyScreen.findElementByName(hidename) != null)
			mapEditorNiftyScreen.findElementByName(hidename).hide();
	}

	public void show(String showname) {
		if (mapEditorNiftyScreen.findElementByName(showname) != null)
			mapEditorNiftyScreen.findElementByName(showname).show();
	}

	/*
	 * NIFTY Functions end
	 */

	/* *
	 * ###### START BUTTON FUNCTIONS ###### *
	 */

	/*
	 * Help Button Function
	 */

	public void help() {
		if(!gui.getMapEditorScreen().getMapEditorFunctions().isWalked()){
			gui.getMapEditorScreen().getMapEditorFunctions().walk(true);
		}else{
			gui.getMapEditorScreen().getMapEditorFunctions().resetWalkCreep();
		}
	}

	/*
	 * Help Button Function end
	 */

	/*
	 * Exit Button Function
	 */

	public void exit() {
		gui.getMapEditorScreen().getMapEditorFunctions().walk(false);
		gui.getMapEditorScreen().getMapEditorFunctions().resetWalkCreep();
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					if (!mapEditorScreen.getMapEditorFunctions().isSaved()) {
						popupOpen = true;
						gui.getNifty().showPopup(
								gui.getNifty().getScreen("mapeditor"),
								savePopup.getSavePopup().getId(), null);

						while (!mapEditorScreen.getMapEditorFunctions()
								.isSaved() && !cancelClicked) {
							Thread.sleep(20);
						}
						cancelClicked = false;
						Thread.sleep(150);
						popupOpen = false;
						hideAllBordersClicked();
						gui.getMapEditorScreen()
								.getDownloadMapPopup()
								.findNiftyControl("mapdownloadlist",
										ListBox.class).clear();
						exitClicked = true;
						mapEditorScreen.getMapEditorFunctions().newMap();
						gui.getStart().getConnection().sendMessage("LOGOUT");
						gui.getStart().getConnection().reconnect();
						gui.setFollowingScreen(gui.getLoginScreen());
						MapRepository.clear();
						loggedIn = false;
					} else {
						hideAllBordersClicked();
						gui.getMapEditorScreen()
								.getDownloadMapPopup()
								.findNiftyControl("mapdownloadlist",
										ListBox.class).clear();
						exitClicked = true;
						mapEditorScreen.getMapEditorFunctions().newMap();
						gui.getStart().getConnection().sendMessage("LOGOUT");
						gui.getStart().getConnection().reconnect();
						gui.setFollowingScreen(gui.getLoginScreen());
						MapRepository.clear();
						loggedIn = false;
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	/*
	 * Exit Button Function end
	 */

	/*
	 * New Map Button Function
	 */

	public void newMap() {
		gui.getMapEditorScreen().getMapEditorFunctions().walk(false);
		gui.getMapEditorScreen().getMapEditorFunctions().resetWalkCreep();
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					if (!mapEditorScreen.getMapEditorFunctions().isSaved()) {
						popupOpen = true;
						gui.getNifty().showPopup(
								gui.getNifty().getScreen("mapeditor"),
								savePopup.getSavePopup().getId(), null);

						while (!mapEditorScreen.getMapEditorFunctions()
								.isSaved() && !cancelClicked) {
							Thread.sleep(20);
						}
						cancelClicked = false;
						popupOpen = false;
						hideAllBordersClicked();
						active = Clickable.NOTHING;
						gui.getMapEditorScreen().getMapEditorFunctions()
								.newMap();
					} else {
						hideAllBordersClicked();
						active = Clickable.NOTHING;
						gui.getMapEditorScreen().getMapEditorFunctions()
								.newMap();
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	/*
	 * New Map Button Function
	 */

	/*
	 * Load Button Function
	 */

	public void load() {
		gui.getMapEditorScreen().getMapEditorFunctions().walk(false);
		gui.getMapEditorScreen().getMapEditorFunctions().resetWalkCreep();
		popupOpen = true;
		mapEditorScreen.getNiftyFileChooser().open(
				new NiftyFileChooseInvoker() {
					@Override
					public void invokeWhenFinished(File file) {
						ZipInputStream zipIn = null;
						try {
							zipIn = new ZipInputStream(
									new FileInputStream(file));
						} catch (Exception e) {
							e.printStackTrace();
						}

						FileOutputStream fout;

						File picture = null;
						File map = null;
						int counter = 0;

						ZipEntry ze = null;

						try {
							while ((ze = zipIn.getNextEntry()) != null) {

								counter++;
								if (counter > 2) {
									return;
								}

								if (ze.getName().contains(".jpg")) {
									picture = File.createTempFile("picture",
											".jpg");
									fout = new FileOutputStream(picture);
								} else if (ze.getName().contains(".map")) {
									map = File.createTempFile("map", ".map");
									fout = new FileOutputStream(map);
								} else {
									return;
								}
								for (int c = zipIn.read(); c != -1; c = zipIn.read()) {
									fout.write(c);
								}
								zipIn.closeEntry();
								fout.flush();
								fout.close();
							}
						} catch (Exception e) {
							e.printStackTrace();
						}

						if (map == null || picture == null) {
							return;
						}

						int constructable[][] = new int[16][16];
						LinkedList<Point> path = new LinkedList<Point>();
						LinkedList<Point> centeredPath = new LinkedList<Point>();
						Point centeredPoint = new Point();
						Point convertedPoint = new Point();

						try {
							constructable = mapEditorScreen
									.getMapEditorFunctions().getConstructable(
											map);
							path = mapEditorScreen.getMapEditorFunctions()
									.getPath(map);
						} catch (IOException e) {
							e.printStackTrace();
						}

						for (Point point : path) {
							convertedPoint = mapEditorScreen
									.getMapEditorFunctions().test(point);
							centeredPoint = mapEditorScreen
									.getMapEditorFunctions().centerCoordinates(
											convertedPoint);
							centeredPath.add(centeredPoint);
						}

						mapEditorScreen.getMapEditorFunctions().setTextureFile(
								picture);
						mapEditorScreen.getMapEditorFunctions()
								.setConstructible(constructable);
						mapEditorScreen.getMapEditorFunctions().setPath(
								centeredPath);
						mapEditorScreen.getMapEditorFunctions()
								.addPointstoList(centeredPath);

						latestFile = file;
						popupOpen = false;
					}
				}, new String[] { "zip" }, false);
	}

	/*
	 * Load Button Function end
	 */

	/*
	 * Save and Upload Function
	 */

	public void saveAndUploadMethod(File file, boolean upload) {
		ZipOutputStream zipOut = null;
		ZipOutputStream server = null;
		Connection connection = gui.getStart().getConnection();
		String mapname = "";
		byte[] buf = new byte[32768];
		int version = 1;

		String[] str = file.getName().split("\\.");
		for (int i = 0; i < str.length - 1; i++) {
			mapname += str[i];
		}

		if (upload) {
			for (Map map : gui.getStart().getModel().getMaps()) {
				if (map.getName().equals(mapname)) {
					version = map.getVersion() + 1;
					break;
				}
			}
		}

		try {
			File map = File.createTempFile(mapname, ".map");

			zipOut = new ZipOutputStream(new FileOutputStream(file, false));
			server = new ZipOutputStream(new BufferedOutputStream(connection
					.getSocket().getOutputStream(), 10000000));

			FileWriter writer = new FileWriter(map, false);

			writer.write("###");
			writer.write(System.getProperty("line.separator"));
			writer.write("### " + mapname);
			writer.write(System.getProperty("line.separator"));
			writer.write("###");
			writer.write(System.getProperty("line.separator"));
			writer.write(System.getProperty("line.separator"));
			writer.write("# VERSION");
			writer.write(System.getProperty("line.separator"));
			writer.write("VERSION: " + version);
			writer.write(System.getProperty("line.separator"));
			writer.write(System.getProperty("line.separator"));
			writer.write("# OWNER");
			writer.write(System.getProperty("line.separator"));
			writer.write("OWNER: Team-H");
			writer.write(System.getProperty("line.separator"));
			writer.write(System.getProperty("line.separator"));
			writer.write(mapname + ".jpg");
			writer.write(System.getProperty("line.separator"));
			writer.write(System.getProperty("line.separator"));
			writer.write("SET_ALPHA_BACKGROUND_COLOR:OFF ");
			writer.write(System.getProperty("line.separator"));
			writer.write(System.getProperty("line.separator"));

			int[][] con = mapEditorScreen.getMapEditorFunctions()
					.getConstructible();
			for (int i = 0; i < con.length; i++) {
				for (int j = 0; j < con[i].length; j++) {
					if (con[i][j] == 2) {
						writer.write(i + ";" + j);
						writer.write(System.getProperty("line.separator"));
					}
				}
			}

			writer.write(System.getProperty("line.separator"));

			Point start = mapEditorScreen.getMapEditorFunctions()
					.getStartPoint();
			if (start != null) {
				start = mapEditorScreen.getMapEditorFunctions()
						.reverseCoords(
								mapEditorScreen.getMapEditorFunctions()
										.getStartPoint());
				writer.write((int) start.getX() + "," + (int) start.getY());
				writer.write(System.getProperty("line.separator"));
			}

			for (Point point : mapEditorScreen.getMapEditorFunctions()
					.getPath()) {
				Point x = mapEditorScreen.getMapEditorFunctions()
						.reverseCoords(point);
				writer.write((int) x.getX() + "," + (int) x.getY());
				writer.write(System.getProperty("line.separator"));
			}

			Point end = mapEditorScreen.getMapEditorFunctions().getEndPoint();

			if (end != null) {
				end = mapEditorScreen.getMapEditorFunctions().reverseCoords(
						mapEditorScreen.getMapEditorFunctions().getEndPoint());
				writer.write((int) end.getX() + "," + (int) end.getY());
			}

			writer.flush();
			writer.close();

			files = new File[2];
			files[0] = map;
			files[1] = mapEditorScreen.getMapEditorFunctions().getBuffer()
					.getAbsoluteFile();

			for (int i = 0; i < 2; i++) {
				FileInputStream in = new FileInputStream(files[i]);

				if (i == 0) {
					zipOut.putNextEntry(new ZipEntry(mapname + ".map"));
					if (upload) {
						server.putNextEntry(new ZipEntry(mapname + ".map"));
					}
				} else {
					zipOut.putNextEntry(new ZipEntry(mapname + ".jpg"));
					if (upload) {
						server.putNextEntry(new ZipEntry(mapname + ".jpg"));
					}
				}

				int len;
				while ((len = in.read(buf)) > 0) {
					zipOut.write(buf, 0, len);
					if (upload) {
						server.write(buf, 0, len);
					}
				}
				zipOut.closeEntry();
				if (upload) {
					server.closeEntry();
				}
				in.close();
			}
			zipOut.finish();
			zipOut.close();

			latestFile = file;

			if (upload) {
				if (mapEditorScreen.getMapEditorFunctions().getErrors().size() > 0) {
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
								showErrorPopup();
								Thread.sleep(20);
								gui.addEvent(new Event("upload", ""));
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}).start();

				} else {
					server.finish();
					try {
						Thread.sleep(500);
					} catch (Exception e) {
						e.printStackTrace();
					}
					connection.sendMessage("UPLOAD MAP");
					try {
						Thread.sleep(500);
					} catch (Exception e) {
						e.printStackTrace();
					}
					connection.sendMessage("UPLOAD "
							+ (int) (latestFile.length()));

					server.flush();
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*
	 * Save and Upload Function end
	 */

	/*
	 * Save Button Function
	 */

	public void save() {
		gui.getMapEditorScreen().getMapEditorFunctions().walk(false);
		gui.getMapEditorScreen().getMapEditorFunctions().resetWalkCreep();
		popupOpen = true;

		mapEditorScreen.getNiftyFileChooser().open(
				new NiftyFileChooseInvoker() {
					@Override
					public void invokeWhenFinished(File file) {
						saveAndUploadMethod(file, false);
						mapEditorScreen.getMapEditorFunctions().setSaved(true);
						System.out.println(mapEditorScreen
								.getMapEditorFunctions().isSaved());
						popupOpen = false;
					}
				}, new String[] { "zip" }, true);
	}

	/*
	 * Save Button Function end
	 */

	/*
	 * Upload Button Function
	 */

	public void upload() {
		gui.getMapEditorScreen().getMapEditorFunctions().walk(false);
		gui.getMapEditorScreen().getMapEditorFunctions().resetWalkCreep();
		if (!gui.getStart().getConnection().isOnline()) {
			mapEditorScreen.showIsOfflinePopup();
			return;
		}

		popupOpen = true;

		if (!loggedIn) {
			setUploadClicked(true);
			gui.getNifty().showPopup(gui.getNifty().getScreen("mapeditor"),
					mapEditorScreen.getDownloadMapPopup().getId(), null);

			new Thread(new Runnable() {
				@Override
				public void run() {

					try {
						Thread.sleep(20);

						reactOnEnter("eingabePasswort");
						reactOnEnter("eingabeName");
						if (isExitClicked()) {
							changeVisibility("mapDownloadLoginPanel",
									"mapDownloadPanel");
							mapEditorNiftyScreen
									.findElementByName("wrongLogin")
									.setVisible(false);
						}

					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}).start();
		} else if (loggedIn) {

			mapEditorScreen.getNiftyFileChooser().open(
					new NiftyFileChooseInvoker() {
						@Override
						public void invokeWhenFinished(File file) {
							saveAndUploadMethod(file, true);
							mapEditorScreen.getMapEditorFunctions().setSaved(
									true);
							popupOpen = false;
						}
					}, new String[] { "zip" }, true);
		}
	}

	/*
	 * Upload Button Function end
	 */

	/*
	 * Background Button Function
	 */

	public void background() {
		gui.getMapEditorScreen().getMapEditorFunctions().walk(false);
		gui.getMapEditorScreen().getMapEditorFunctions().resetWalkCreep();
		popupOpen = true;
		mapEditorScreen.getNiftyFileChooser().open(
				new NiftyFileChooseInvoker() {
					@Override
					public void invokeWhenFinished(File file) {
						mapEditorScreen.getMapEditorFunctions().setTextureFile(
								file);
						mapEditorScreen.getMapEditorFunctions().setSaved(false);
						popupOpen = false;
					}
				}, new String[] { "jpg", "JPG", "jpeg", "JPEG" }, false);
	}

	/*
	 * Background Button Function end
	 */

	/*
	 * Map Download Button Functions
	 */

	public void downloadButtonclick() {
		gui.getMapEditorScreen().getMapEditorFunctions().walk(false);
		gui.getMapEditorScreen().getMapEditorFunctions().resetWalkCreep();
		if (!gui.getStart().getConnection().isOnline()) {
			mapEditorScreen.showIsOfflinePopup();
			return;
		}

		popupOpen = true;
		gui.getNifty().showPopup(gui.getNifty().getScreen("mapeditor"),
				mapEditorScreen.getDownloadMapPopup().getId(), null);

		new Thread(new Runnable() {
			@Override
			public void run() {

				try {
					Thread.sleep(20);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				reactOnEnter("eingabePasswort");
				reactOnEnter("eingabeName");
				if (isExitClicked()) {
					changeVisibility("mapDownloadLoginPanel",
							"mapDownloadPanel");
					mapEditorNiftyScreen.findElementByName("wrongLogin")
							.setVisible(false);
				}

			}
		}).start();
	}

	public void loginbuttonclick() {
		String eingabe = mapEditorNiftyScreen.findNiftyControl("eingabeName",
				TextField.class).getText();
		String passwort = mapEditorNiftyScreen.findNiftyControl(
				"eingabePasswort", TextField.class).getText();

		mapEditorNiftyScreen.findNiftyControl("eingabeName", TextField.class)
				.setText("");
		mapEditorNiftyScreen.findNiftyControl("eingabePasswort",
				TextField.class).setText("");

		if ((eingabe.isEmpty()) && (passwort.isEmpty())) {
			gui.getStart().getConnection()
					.sendMessage("login" + " " + "x" + " " + "x");
		} else {
			gui.getStart().getConnection()
					.sendMessage("login" + " " + eingabe + " " + passwort);
		}
		changeVisibility("LoginNameTextfieldEffect",
				"LoginPasswordTextfieldEffect");
		setLoginButtonClicked(true);
	}

	public void backToMapEditorButtonclick() {
		popupOpen = false;
		gui.getNifty()
				.closePopup(mapEditorScreen.getDownloadMapPopup().getId());
	}

	public void mapdownloadbuttonclick() {
		mapEditorScreen.getMapEditorFunctions().newMap();
		String mapName = (String) mapEditorNiftyScreen.findNiftyControl(
				"mapdownloadlist", ListBox.class).getFocusItem();
		ConnectionHandler connectionHandler = (ConnectionHandler)gui.getStart().getConnection().getMessageReceiver();
		MapDownload download = connectionHandler.getMapDownload();
		int constructable[][] = new int[16][16];
		LinkedList<Point> path = new LinkedList<Point>();
		LinkedList<Point> centeredPath = new LinkedList<Point>();
		Point centeredPoint = new Point();
		Point convertedPoint = new Point();

		gui.getStart().getConnection().sendMessage("DOWNLOAD MAP " + mapName);

		while (!connectionHandler.isEot()) {
			try {
				Thread.sleep(20);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		connectionHandler.setEot(false);

		try {
			constructable = mapEditorScreen.getMapEditorFunctions()
					.getConstructable(download.getMap());
			path = mapEditorScreen.getMapEditorFunctions().getPath(
					download.getMap());
		} catch (IOException e) {
			e.printStackTrace();
		}

		for (Point point : path) {
			convertedPoint = mapEditorScreen.getMapEditorFunctions()
					.test(point);
			centeredPoint = mapEditorScreen.getMapEditorFunctions()
					.centerCoordinates(convertedPoint);
			centeredPath.add(centeredPoint);
		}

		mapEditorScreen.getMapEditorFunctions().setTextureFile(
				download.getPicture());
		mapEditorScreen.getMapEditorFunctions().setConstructible(constructable);
		mapEditorScreen.getMapEditorFunctions().setPath(centeredPath);
		mapEditorScreen.getMapEditorFunctions().addPointstoList(centeredPath);

		gui.getNifty()
				.closePopup(mapEditorScreen.getDownloadMapPopup().getId());
		popupOpen = false;

	}

	/*
	 * Download Button Functions end
	 */

	/* *
	 * ###### END BUTTON FUNCTIONS ###### *
	 */

	/*
	 * Save Popup Function
	 */
	public void saveCurrentChanges() {
		gui.getNifty().closePopup(savePopup.getSavePopup().getId());
		save();
	}

	public void closeSavePopup() {
		gui.getNifty().closePopup(savePopup.getSavePopup().getId());
		mapEditorScreen.getMapEditorFunctions().setSaved(true);
	}

	/*
	 * Save Popup Function end
	 */

	/*
	 * Error Popup Function
	 */

	public void showErrorPopup() {
		gui.getNifty().showPopup(gui.getNifty().getScreen("mapeditor"),
				errorPopup.getErrorPopup().getId(), null);
	}

	public void closeErrorPopup() {
		gui.getNifty().closePopup(errorPopup.getErrorPopup().getId());
		popupOpen = false;
		mapEditorScreen.getMapEditorFunctions().setSaved(true);
	}

	/*
	 * Error Popup Function end
	 */

	/*
	 * ### SETTER AND GETTER ###
	 */

	public void setInformationtext(Element informationtext) {
		this.informationtext = informationtext;
	}

	public Element getInformationtext() {
		return informationtext;
	}

	public boolean isExitClicked() {
		return exitClicked;
	}

	public void setExitClicked(boolean exitClicked) {
		this.exitClicked = exitClicked;
	}

	public void niftyFileChooserOK() {
		mapEditorScreen.getNiftyFileChooser().ok();
	}

	public void niftyFileChooserCancel() {
		mapEditorScreen.getNiftyFileChooser().cancel();
		popupOpen = false;
		cancelClicked = true;
	}

	public void niftyFileChooserClick(String click) {
		mapEditorScreen.getNiftyFileChooser().clicked(click);
	}

	public File getLatestSaved() {
		return latestFile;
	}

	public void setLatestSaved(File latestSaved) {
		this.latestFile = latestSaved;
	}

	public boolean isLoggedIn() {
		return loggedIn;
	}

	public void setLoggedIn(boolean loggedIn) {
		this.loggedIn = loggedIn;
	}

	public boolean isUploadClicked() {
		return uploadClicked;
	}

	public void setUploadClicked(boolean uploadClicked) {
		this.uploadClicked = uploadClicked;
	}

	public void isOfflineOKClick() {
		mapEditorScreen.closeIsOfflinePopup();
	}

	public GUI getGui() {
		return gui;
	}

	public void setButton(int button) {
		this.button = button;
	}

	public boolean isCancelClicked() {
		return cancelClicked;
	}

	public void setCancelClicked(boolean cancelClicked) {
		this.cancelClicked = cancelClicked;
	}

	public Screen getMapEditorNiftyScreen() {
		return mapEditorNiftyScreen;
	}

	public void addPointToList(String addMe, int index) {
		@SuppressWarnings("unchecked")
		ListBox<String> listBox = mapEditorNiftyScreen.findNiftyControl(
				"wayPointList", ListBox.class);
		listBox.insertItem(addMe, index);
	}

	public void deletePointFromList(String removeMe) {
		@SuppressWarnings("unchecked")
		ListBox<String> listBox = mapEditorNiftyScreen.findNiftyControl(
				"wayPointList", ListBox.class);
		listBox.removeItem(removeMe);
	}

	public void selectItemFromList(String findMe) {
		@SuppressWarnings("unchecked")
		ListBox<String> listBox = mapEditorNiftyScreen.findNiftyControl(
				"wayPointList", ListBox.class);

		listBox.selectItem(findMe);
	}

	public void clearList() {
		mapEditorNiftyScreen.findNiftyControl("wayPointList", ListBox.class)
				.clear();
	}

	private int getPointOutOfList(String listText) {
		return Integer.valueOf(listText.substring(0, 3));
	}

	@NiftyEventSubscriber(id = "wayPointList")
	public void onMyListBoxSelectionChanged(final String id,
			final ListBoxSelectionChangedEvent<String> event) {
		List<String> selection = event.getSelection();
		for (String selectedItem : selection) {
			mapEditorScreen.getMapEditorFunctions().selectByIndex(
					getPointOutOfList(selectedItem));
		}
	}

	public void setLoginButtonClicked(boolean loginButtonClicked) {
		this.loginButtonClicked = loginButtonClicked;
	}

	public boolean isLoginButtonClicked() {
		return loginButtonClicked;
	}

}
